using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Security;
using System.Text;

using Dragon.Prototype1.Infrastructure.Controls;
using Dragon.Prototype1.Infrastructure.FormBuilder;

using Dragon.Prototype1.Service;
using LINQtoSQLDataProvider;

namespace Dragon.Prototype1.Web.Controllers
{
    public class RoleController : Controller
    {
        public ActionResult GetUsersByRoleId(string sidx, string sord, int page, int rows, Guid roleid)
        {
            var users=RoleService.GetUsersByRoleId(roleid);
            int pageno = (page - 1) > 0 ? page - 1 : 0;
            int totalnum = users.Count;
            var jsonData = new
            {
                total = totalnum / rows + 1,
                page = page,
                records = totalnum,
                rows = (from row in users.Skip(pageno * rows).Take(rows)
                    select new
                    {
                        id = row.UserId.ToString(),
                        cell = new string[]
                        {
                            row.UserId.ToString(),
                            row.UserName,
                            row.Email,
                            string.Empty
                        }
                    }).ToArray()
            };
            return Json(jsonData);
        }

        public ActionResult ListData(string sidx, string sord, int page, int rows, string roleName)
        {
            StringBuilder whereString = new StringBuilder();
            
            string sortString=string.Format("{0} {1}",sidx,sord);
            if(!string.IsNullOrEmpty(roleName))
                whereString.AppendFormat("LoweredRoleName like '%{0}%'", roleName.ToLower());
            var roles=RoleService.GetRoles(page, rows, sortString, whereString.Length==0?null:whereString.ToString());

            int totalnum = roles.Count ;
            var jsonData = new
            {
                total = totalnum / rows + 1,
                page = page,
                records = totalnum,
                rows = (from row in roles
                        select new
                        {
                            id = row.RoleId.ToString(),
                            cell = new string[]
                            {
                                row.RoleId.ToString(),
                                row.RoleName,
                                row.Description,
                            }
                        }).ToArray()
            };
            return Json(jsonData);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(string id, string oper, FormCollection collection)
        {
            if (oper == "del")
            {
                string[] ids = id.Split(new char[] { ',' });
                foreach (string i in ids)
                {
                    if (RoleService.DeleteRole(new Guid(id)) == false)
                        throw new InvalidOperationException("delete user failed");
                }
            }
            return Json(true);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddUsersToRole(Guid[] subpanel_id, Guid roleid)
        {
            var users = RoleService.AddUsersToRole(roleid, subpanel_id);

            var jsonData = (from row in users
                            select new
                            {
                                id = row.UserId.ToString(),
                                cell = new
                                {
                                id = row.UserId.ToString(),
                                username=row.UserName,
                                email=row.Email,
                                }
                            }).ToArray();
            
            return Json(jsonData);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(Guid id)
        {
            Role role=RoleService.GetRole(id);

            jQueryFormBuilder formbuilder = new jQueryFormBuilder();
            formbuilder.CssClass = "tabcontainer";
            FormGroup formgroup1 = new FormGroup("BASICINFO");
            formgroup1.ColumnNumber = 2;
            formgroup1.Width = "100%";
            formgroup1.AddLabeledTextBox("RoleName", this.Resource("ROLE", "ROLENAME"),role.RoleName, true, true);
            formgroup1.AddLabeledTextBox("Desc", this.Resource("Global", "DESCRIPTION"), role.Description, "normaltextarea", false, true, true, false);
            formbuilder.Groups.Add(formgroup1);

            ViewData["roleid"] = id;
            return View(formbuilder);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Guid roleid, string roleName, string desc)
        {
            
            return View("Index");
        }

        private jQueryFormBuilder CreateForm()
        {
            jQueryFormBuilder formbuilder = new jQueryFormBuilder();
            formbuilder.CssClass = "tabcontainer";
            FormGroup formgroup1 = new FormGroup("BASICINFO");
            formgroup1.ColumnNumber = 2;
            formgroup1.Width = "100%";
            formgroup1.AddLabeledTextBox("RoleName", this.Resource("ROLE", "ROLENAME"), true,true);
            formgroup1.AddLabeledTextBox("Desc", this.Resource("Global", "DESCRIPTION"), string.Empty, "longtextarea", false, true, true, false);
            formbuilder.Groups.Add(formgroup1);
            return formbuilder;
        }

        public ActionResult Create()
        {
            return View(CreateForm());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string roleName,string desc)
        {
            RoleService.CreateRole(roleName, desc);
            return View("Index");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RemoveUserFromRole(Guid userid,Guid roleid)
        {
            var result=RoleService.RemoveUserFromRole(userid, roleid);
            return Json(result);
        }
    }
}
